package com.seed.core.aspect;

import com.seed.core.annotation.FuzzyQuery;
import com.seed.core.pojo.entity.SeedBaseEntity;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;

/**
 * @author gchiaway
 * 日期: 2020-08-28
 * 时间: 17:28
 */
@Aspect
@Component
@Slf4j
public class FuzzyQueryAspect {


    @Pointcut("execution(* com.business..*.*Controller.queryPageList(..))) ")
    public void queryPageList() {

    }

    @Pointcut("execution(* com.business..*.*Controller.queryList(..))) ")
    public void queryList() {

    }

    /**
     * 前置通知：目标方法调用之前执行的代码
     *
     * @param jp
     */
    @Before(value = "queryPageList() || queryList()")
    public void doBefore(JoinPoint jp) {
        Object[] args = jp.getArgs();
        if (StringUtils.isEmpty(args) || args.length <= 0) {
            return;
        }
        for (Object arg : args) {
            if (arg instanceof SeedBaseEntity) {
                try {
                    this.setFuzzyQuery((SeedBaseEntity) arg);
                } catch (Exception e) {
                    return;
                }
            }
        }
    }

    /**
     * 设置模糊查询
     *
     * @param query 查询条件
     */
    private void setFuzzyQuery(SeedBaseEntity query) throws Exception {
        for (Field field : oConvertUtils.getAllFields(query)) {
            if (field.getAnnotation(FuzzyQuery.class) != null) {
                FuzzyQuery fuzzyQuery = field.getAnnotation(FuzzyQuery.class);
                boolean rightLeftQuery = fuzzyQuery.rightLeftQuery();
                boolean rightQuery = fuzzyQuery.rightQuery();
                boolean leftQuery = fuzzyQuery.leftQuery();
                field.setAccessible(true);
                String fieldValue = (String) field.get(query);
                if (StringUtils.isEmpty(fieldValue)) {
                    continue;
                }
                if (rightLeftQuery) {
                    fieldValue = "*" + fieldValue + "*";
                } else if (rightQuery) {
                    fieldValue = fieldValue + "*";
                } else if (leftQuery) {
                    fieldValue = "*" + fieldValue;
                }
                field.set(query, fieldValue);
            }
        }
    }
}
